<template>
  <div style="width: 1200px;margin: 200px auto;">
    <h2>请选择注册类型</h2>
    <div style="margin: 40px auto; text-align: center">
      <el-radio v-model="memberType" label="Personal" border>个人</el-radio>
      <el-radio v-model="memberType" label="Delegation" border>团体</el-radio>
      <el-radio v-model="memberType" label="PersonalDelegation" border>个人、团体</el-radio>
    </div>
    <div align="center">
      <el-button @click="handleNextOperation()">下一步</el-button>
    </div>
    <!-- 实名认证 -->
    <el-dialog title="实名认证" width="880px" class="gl_dialog_TitleLine" :close-on-click-modal="false" :visible.sync="dialogRealName">
      <div style="text-align: center">
        <el-radio-group v-model="radioRealNameTyepe">
          <el-radio-button label="NameNumber">号码验证</el-radio-button>
          <el-radio-button label="OCR">证件验证</el-radio-button>
        </el-radio-group>
      </div>
      <div style="height: 250px;margin-top: 30px">
        <el-form ref="refFormIDCard" :model="createRegisterInput" :rules="CreateRegisterInput_Rules">
          <el-row :gutter="20">
            <!-- 号码验证 -->
            <template v-if="radioRealNameTyepe === 'NameNumber'">
              <el-form-item label="姓名" prop="idCard.name" label-width="180px">
                <el-input v-model="createRegisterInput.idCard.name" size="mini" clearable style="width: 80%;" placeholder="请输入姓名" />
              </el-form-item>
              <el-form-item label="身份号码" prop="idCard.idCardNumber" label-width="180px">
                <el-input v-model="createRegisterInput.idCard.idCardNumber" size="mini" clearable style="width: 80%;" placeholder="请输入身份号码" />
              </el-form-item>
            </template>
            <!-- 证件验证 -->
            <template v-if="radioRealNameTyepe === 'OCR'">
              <el-col :span="12">
                <div class="gl_fl">
                  <el-form-item prop="idCard.idCardFrontImage" label="身份证正面">
                    <el-input v-model="createRegisterInput.idCard.idCardFrontImage" style="display: none" />
                    <upload-card
                      ref="uploadFile"
                      :file-name="createRegisterInput.idCard.idCardFrontImage"
                      :action="action"
                      :show-file-list="false"
                      :limit="1"
                      file-type="file"
                      format-file=".pdf,.jpg,.png"
                      :default-file-url="idCardFrontImage"
                      @uploadSuccess="photoSaveFront"
                    />
                  </el-form-item>
                </div>
              </el-col>
              <el-col :span="12">
                <div class="gl_fl">
                  <el-form-item prop="idCard.idCardBackImage" label="身份证反面">
                    <el-input v-model="createRegisterInput.idCard.idCardBackImage" style="display: none" />
                    <upload-card
                      ref="uploadFile"
                      :file-name="createRegisterInput.idCard.idCardBackImage"
                      :action="action"
                      :show-file-list="false"
                      :limit="1"
                      file-type="file"
                      format-file=".pdf,.jpg,.png"
                      :default-file-url="idCardBackImage"
                      @uploadSuccess="photoSaveBack"
                    />
                  </el-form-item>
                </div>
              </el-col>
            </template>
          </el-row>
        </el-form>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button size="mini" @click="dialogRealName = false">{{ $t('button.cancel') }}</el-button>
        <el-button size="mini" type="primary" :loading="submitLoading" @click="submitIndRegister">{{ $t('button.save') }}</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import UploadCard from './uploadCard';
import { CreateRegisterInput_Rules } from '@/lib/validate/register';
export default {
  name: 'ChooseType',
  components: {
    UploadCard
  },
  data () {
    return {
      memberType: 'Personal',
      dialogRealName: false,
      radioRealNameTyepe: 'NameNumber',
      // 新建机构
      createDelegationInput: new SiSTKWEventsManagementCreateDelegationInput(),
      // 新建注册
      createRegisterInput: new SiSTKWEventsManagementRegisterUserInput(),
      CreateRegisterInput_Rules: new CreateRegisterInput_Rules(),
      action: `${WEB_CONFIG.VUE_APP_STATIC_FILE_RUL}/api/upload/image`,
      submitLoading: false,
      idCardFrontImage: '',
      idCardBackImage: ''
    };
  },
  watch: {
    'dialogRealName': function(val) {
      if (!val) {
        this.radioRealNameTyepe = 'NameNumber';
        this.$refs['refFormIDCard'].resetFields();
        this.createRegisterInput = new SiSTKWEventsManagementRegisterUserInput();
      }
    }
  },
  methods: {
    handleNextOperation() {
      this.createDelegationInput.delegationTypeCode = null; // 默认为null
      this.createDelegationInput.imagePath = null; // 默认为null，否则无法通过
      this.createDelegationInput.isApproved = true;
      if (this.memberType === 'Delegation') {
        // 团体 —— 直接注册，注册成功去团体主页
        api_POST_EventsManagementUserRegisterUser({ userTypeCode: this.memberType }).then(res => {
          this.$store.dispatch('user/getCurrentUserType');
          this.$router.push({ path: '/myCenter/team/info' });
        });
      } else {
        // 个人、团体 （包含个人注册需要先进行实名认证）
        this.dialogRealName = true;
      }
    },
    // 实名认证
    submitIndRegister() {
      const _this = this;
      // 号码校验
      // if (_this.radioRealNameTyepe === 'NameNumber') {
      _this.$refs['refFormIDCard'].validate(valid => {
        if (valid) {
          this.submitLoading = true;
          this.createRegisterInput.userTypeCode = this.memberType;
          this.createRegisterInput.idCard.VerifyMethod = this.radioRealNameTyepe;
          api_POST_EventsManagementUserRegisterUser(this.createRegisterInput).then(res => {
            _this.$store.dispatch('user/getCurrentUserType');
            _this.$router.push({ path: '/myCenter/individual/info' });
          }).catch(() => {
            this.submitLoading = false;
            this.$message({ type: 'error', message: '用户注册失败！' });
          });
        } else {
          return false;
        }
      });
    },
    // 回显
    photoSaveFront(fileUrl) {
      this.httpRequest(fileUrl, 'idCardFrontImage');
    },
    // 回显
    photoSaveBack(fileUrl) {
      this.httpRequest(fileUrl, 'idCardBackImage');
    },
    httpRequest(data, img) {
      this.getBase64(data).then(resBase64 => {
        this.$set(this.createRegisterInput.idCard, img, resBase64.split(',')[1]);
        if (img === 'idCardFrontImage') {
          this.idCardFrontImage = resBase64;
        }
        if (img === 'idCardBackImage') {
          this.idCardBackImage = resBase64;
        }
      });
    },
    // 这个file参数 也就是文件信息，你使用 插件 时 你就可以打印出文件信息 看看嘛
    getBase64(file) {
      return new Promise((resolve, reject) => {
        const reader = new FileReader();
        let fileResult = '';
        reader.readAsDataURL(file);// 开始转
        reader.onload = function() {
          fileResult = reader.result;
        }; // 转 失败
        reader.onerror = function(error) {
          reject(error);
        }; // 转 结束  咱就 resolve 出去
        reader.onloadend = function() {
          resolve(fileResult);
        };
      });
    }
  }
};
</script>
<style scoped>
.imgt_upload {
  width: 240px;
  height: 150px;
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  overflow: hidden;
}
.imgt_upload:hover {
  border-color: #409EFF;
}
</style>
